package com.pinyougou.user.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.pinyougou.mapper.TbUserMapper;
import com.pinyougou.pojo.TbUser;
import com.pinyougou.user.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.Destination;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service(timeout = 3000)
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Destination destination;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private TbUserMapper userMapper;

    /**
     * 验证验证码是否存在
     * @param phone
     * @param smscode
     * @return
     */
    @Override
    public boolean checkSmsCode(String phone, Integer smscode) {

        Integer code = (Integer) redisTemplate.boundValueOps("smsCode_" + phone).get();

        System.out.println(phone+":获取到的验证码为:"+code);

        return smscode.equals(code);

    }

    /**
     * 用户添加
     * @param user
     */
    @Override
    public void addUser(TbUser user) {

        user.setCreated(new Date());//创建日期
        user.setUpdated(new Date());//修改日期
        String password = DigestUtils.md5Hex(user.getPassword());//对密码加密
        user.setPassword(password);
        userMapper.insert(user);

    }

    /**
     * 验证码生成及加入消息队列
     * @param phone
     */
    @Override
    public void createCodeAndSaveQueue(String phone) {

        //生成6位验证码
        Random random = new Random();

        int code = random.nextInt((999999 + 1) - 100000)+100000;

        //存入redis,5分钟失效
        redisTemplate.boundValueOps("smsCode_"+phone).set(code,5, TimeUnit.MINUTES);

        //消息队列
        HashMap<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code+"");

        //转换
        jmsTemplate.convertAndSend(destination,map);

    }
}
